package com.xxpt.common.auth;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.xxpt.common.annotation.NoAuth;
import com.xxpt.common.constant.SysConstant;
import com.xxpt.common.exception.UnauthorizedException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * 权限拦截器
 * @Author masl - 2020/4/8 10:47
 */
public class AuthHandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 过滤不需要登录的链接
        if (filterNoAuth(request)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        //获取方法上的注解 - NoLogin
        NoAuth noLogin = handlerMethod.getMethod().getAnnotation(NoAuth.class);
        //获取类上的注解
        if (noLogin == null) {
            noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoAuth.class);
        }
        //不需要登录
        if (noLogin != null) {
            return true;
        }
        //检测登录信息
        AuthProperties authProperties = checkLoginInfo(request);
        return doAuthorizationCheck(authProperties);
    }

    /**
     * 检测登录信息
     * @param request
     */
    private AuthProperties checkLoginInfo(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            throw new UnauthorizedException(ValidationErrorCode.USER_NOT_LOGIN);
        }
        String tokenStr = SecureUtil.aes(SysConstant.SESSION_AES_KEY.getBytes()).decryptStr(token);
        AuthProperties authProperties = JSON.parseObject(tokenStr, AuthProperties.class);
        if (authProperties == null) {
            throw new UnauthorizedException(ValidationErrorCode.USER_NOT_LOGIN);
        }
        // 判断token是否存在
        String key = authProperties.getSessionKey();
        /*if (authProperties.getuType().intValue() == UserTypeEnum.PERSON.getVal().intValue()) {
            // 学员key: session前缀+userId+登录终端类型
            key = SysConstant.SESSION_STUDENT_KEY_PREFIX + authProperties.getUid() + ":" + authProperties.getReqSource();
        } else {
            key = SysConstant.SESSION_DEPARTMENT_KEY_PREFIX + authProperties.getUid() + ":" + authProperties.getReqSource();
        }*/
        if (SysConstant.redisTemplate.hasKey(key)) {
            throw new UnauthorizedException(ValidationErrorCode.TOKEN_NON_EXIST);
        }
        return authProperties;
    }

    /**
     * 过滤不需要验证的请求
     * @return
     */
    private boolean filterNoAuth(HttpServletRequest request) {
        String path = request.getServletPath();
        // 过滤不需要登录的链接 ...
        if ("/error".endsWith(path)
                || path.equals("/")
                || Pattern.compile("(swagger-resources/*)").matcher(path).find()//swagger 相关
                || Pattern.compile("(qrcode|/login|logout|/debug|/error)").matcher(path).find()) {
            return true;
        }
        return false;
    }

    /**
     * 验证权限
     */
    protected boolean doAuthorizationCheck(AuthProperties authProperties) {
        return true;
    }
}
